<template>
    <div class="brokerManageDetail">
        <el-breadcrumb separator="/" class="bread-title">
            <el-breadcrumb-item>渠道管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/brokerManage' }">经纪人管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{type2Name[type]}}</el-breadcrumb-item>
        </el-breadcrumb>


        

        <el-tabs v-model="activeName" v-if="type === 'view'">
            <el-tab-pane label="基本信息" name="first">
                <el-form  size="small" :model="form" :rules="rules" ref="form" class="demo-form" label-width="130px">
                    <el-form-item label="角色：" prop="brokerType">
                        <el-select :disabled="type!=='new'" v-model="form.brokerType" placeholder="请选择城市">
                            <el-option
                                    v-for="item in brokerTypeList"
                                    :key="item.id"
                                    :label="item.dicDesc"
                                    :value="item.dicValue">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="城市：" prop="cityId">
                        <el-select v-model="form.cityId" placeholder="请选择城市" disabled>
                            <el-option
                                    v-for="item in allCityList"
                                    :key="item.cityId"
                                    :label="item.city"
                                    :value="item.cityId">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 职业经纪人 -->
                    <el-form-item label="门店编码：" v-if="form.brokerType === '3'" prop="storeCode">
                        {{form.storeCode}}
                    </el-form-item>

                    <el-form-item label="所属公司：" prop="companyId">
                        <el-select v-model="form.companyId" disabled placeholder="请选择所属公司">
                            <el-option
                                    v-for="item in companyList"
                                    :key="item.id"
                                    :label="item.companyName"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- 职业经纪人 -->
                    <el-form-item label="所属门店：" v-if="form.brokerType === '3'" prop="storeId">
                        <el-select v-model="form.storeId" disabled placeholder="请选择所属门店">
                            <el-option
                                    v-for="item in storeList"
                                    :key="item.id"
                                    :label="item.storesName"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- 职业经纪人 -->
                    <el-form-item label="服务板块："  v-if="form.brokerType === '3'" prop="sectionId">
                        <el-select v-model="form.sectionId" disabled placeholder="请选择服务板块">
                            <el-option
                                    v-for="item in sectionList"
                                    :key="item.areaId"
                                    :label="item.areaName"
                                    :value="item.areaId">
                            </el-option>
                        </el-select>
                    </el-form-item>


                    <!-- 销售经理和置业顾问 -->

                    <template v-if="form.brokerType === '6' || form.brokerType === '8'">
                        <el-form-item label="经纪等级：" prop="brokerLevel">
                            <el-select v-model="form.brokerLevel" disabled placeholder="请选择经纪等级">
                                <el-option
                                        v-for="item in brokerLevelList"
                                        :key="item.dicValue"
                                        :label="item.dicDesc"
                                        :value="item.dicValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="工号：" prop="jobNumber">
                            {{form.jobNumber}}
                        </el-form-item>
                        <el-form-item label="基本工资：" prop="basicSalary">
                            {{form.basicSalary}}
                        </el-form-item>
                    </template>


                    <el-form-item label="用户姓名：" prop="brokerName">
                        {{form.brokerName}}
                    </el-form-item>

                    <el-form-item label="用户手机号：" prop="brokerPhone">
                        {{form.brokerPhone}}
                    </el-form-item>
                    <el-form-item label="初始密码：" prop="password">
                        {{form.password}}
                    </el-form-item>
                    <el-form-item label="用户邮箱：" prop="brokerEmail">
                        {{form.brokerEmail}}
                    </el-form-item>


                    <div v-if="form.brokerType === '3' || form.brokerType === '4' || form.brokerType === '5'">
                        <!-- 职业经纪人 -->
                        <el-form-item  label="权限：">
                            <el-checkbox-group v-model="form.competence" disabled>
                                <el-checkbox label="1">新房</el-checkbox>
                                <el-checkbox label="2">保险</el-checkbox>
                                <el-checkbox label="3">产权</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>

                        <el-form-item label="新房分佣比例：" prop="newHouseRate" v-if="form.competence.includes('1')">
                            {{form.newHouseRate}}
                            %
                        </el-form-item>
                        <el-form-item label="保险分佣比例：" prop="insuranceRate" v-if="form.competence.includes('2')">
                            {{form.insuranceRate}}
                            %
                        </el-form-item>
                        <el-form-item label="产权分佣比例：" prop="propertyRate" v-if="form.competence.includes('3')">
                            {{form.propertyRate}}
                            %
                        </el-form-item>

                    </div>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="认证信息" name="second">
                <h5>认证信息</h5>
                <el-form label-width="120px" size="small" :model="brokerInfo">
                    <el-form-item label="姓名：">{{brokerInfo.realName}}</el-form-item>
                    <el-form-item label="证件号码：">{{brokerInfo.idCardNo}}</el-form-item>
                </el-form>
                <h5>证件照片</h5>
                <div class="ml30">
                    <el-image
                            style="width: 200px; height: 200px"
                            :src="brokerInfo.idCardFront"
                            :preview-src-list="[brokerInfo.idCardFront, brokerInfo.idCardBack]">
                    </el-image>
                    <el-image
                            style="width: 200px; height: 200px"
                            :src="brokerInfo.idCardBack"
                            :preview-src-list="[brokerInfo.idCardFront, brokerInfo.idCardBack]">
                    </el-image>
                </div>
                <h5>银行卡信息</h5>
                <el-form label-width="120px" size="small" :model="brokerInfo">
                    <el-form-item label="开户行：">{{brokerInfo.openBankName}}</el-form-item>
                    <el-form-item label="开户支行：">{{brokerInfo.openSubBankName}}</el-form-item>
                    <el-form-item label="收款账号：">{{brokerInfo.bankCardCode}}</el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>


        <el-form size="small" v-else :model="form" :rules="rules" ref="form" class="demo-form" label-width="130px">
            <el-form-item label="角色：" prop="brokerType">
                <el-select :disabled="type!=='new'" v-model="form.brokerType" placeholder="请选择城市">
                    <el-option
                            v-for="item in brokerTypeList"
                            :key="item.id"
                            :label="item.dicDesc"
                            :value="item.dicValue">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="城市：" prop="cityId">
                <el-select v-model="form.cityId" placeholder="请选择城市" filterable @change="getCompanyListByCityId">
                    <el-option
                            v-for="item in allCityList"
                            :key="item.cityId"
                            :label="item.city"
                            :value="item.cityId">
                    </el-option>
                </el-select>
            </el-form-item>

            <!-- 职业经纪人 -->
            <el-form-item label="门店编码：" v-if="form.brokerType === '3'" prop="storeCode">
                <el-input v-model="form.storeCode" style="width: 214px" placeholder="请输入门店编码" @blur="getStoreByNumber"></el-input>
            </el-form-item>

            <el-form-item label="所属公司：" prop="companyId">
                <el-select v-model="form.companyId" filterable :disabled="!form.cityId" placeholder="请选择所属公司" @change="getStoresByCompanyId">
                    <el-option
                            v-for="item in companyList"
                            :key="item.id"
                            :label="item.companyName"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <!-- 职业经纪人 -->
            <el-form-item label="所属门店：" v-if="form.brokerType === '3'" prop="storeId">
                <el-select v-model="form.storeId" filterable :disabled="!form.companyId" placeholder="请选择所属门店" @change="getStoreByNumber('storeId')">
                    <el-option
                            v-for="item in storeList"
                            :key="item.id"
                            :label="item.storesName"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <!-- 职业经纪人 -->
            <el-form-item label="服务板块："  v-if="form.brokerType === '3'" prop="sectionId">
                <el-select v-model="form.sectionId" disabled placeholder="请选择服务板块">
                    <el-option
                            v-for="item in sectionList"
                            :key="item.areaId"
                            :label="item.areaName"
                            :value="item.areaId">
                    </el-option>
                </el-select>
            </el-form-item>


            <!-- 销售经理和置业顾问 -->

            <template v-if="form.brokerType === '6' || form.brokerType === '8'">
                <el-form-item label="经纪等级：" prop="brokerLevel">
                    <el-select v-model="form.brokerLevel" :disabled="!form.companyId" placeholder="请选择经纪等级">
                        <el-option
                                v-for="item in brokerLevelList"
                                :key="item.dicValue"
                                :label="item.dicDesc"
                                :value="item.dicValue">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="工号：" prop="jobNumber">
                    <el-input v-model="form.jobNumber" style="width: 214px" placeholder="请输入工号"></el-input>
                </el-form-item>
                <el-form-item label="基本工资：" prop="basicSalary">
                    <el-input v-model="form.basicSalary" style="width: 214px" placeholder="请输入基本工资"></el-input>
                </el-form-item>
            </template>


            <el-form-item label="用户姓名：" prop="brokerName">
                <el-input v-model="form.brokerName" style="width: 214px" placeholder="请输入用户姓名"></el-input>
            </el-form-item>

            <el-form-item label="用户手机号：" prop="brokerPhone">
                <el-input :disabled="type!=='new'" v-model="form.brokerPhone" style="width: 214px" placeholder="请输入用户手机号"></el-input>
            </el-form-item>
            <el-form-item label="初始密码：" prop="password">
                <el-input v-model="form.password" :disabled="type !== 'edit'" style="width: 214px" placeholder="请输入用户初始密码"></el-input>
            </el-form-item>
            <el-form-item label="用户邮箱：" prop="brokerEmail">
                <el-input v-model="form.brokerEmail" style="width: 214px" placeholder="请输入用户邮箱"></el-input>
            </el-form-item>


            <div v-if="form.brokerType === '3' || form.brokerType === '4' || form.brokerType === '5'">
                <!-- 职业经纪人 -->
                <el-form-item  label="权限：" prop="competence">
                    <el-checkbox-group v-model="form.competence">
                        <el-checkbox label="1">新房</el-checkbox>
                        <el-checkbox label="2">保险</el-checkbox>
                        <el-checkbox label="3">产权</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item label="新房分佣比例：" prop="newHouseRate" v-if="form.competence.includes('1')">
                    <el-input v-model="form.newHouseRate" style="width: 214px" placeholder="请输入新房分佣比例"></el-input>
                    %
                </el-form-item>
                <el-form-item label="保险分佣比例：" prop="insuranceRate" v-if="form.competence.includes('2')">
                    <el-input v-model="form.insuranceRate" style="width: 214px" placeholder="请输入保险分佣比例"></el-input>
                    %
                </el-form-item>
                <el-form-item label="产权分佣比例：" prop="propertyRate" v-if="form.competence.includes('3')">
                    <el-input v-model="form.propertyRate" style="width: 214px" placeholder="请输入产权分佣比例"></el-input>
                    %
                </el-form-item>

            </div>
            

            <el-form-item>
                <el-button type="primary" @click="saveBroker">保存</el-button>
                <el-button @click="returnList()">取消</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>

<script type="text/ecmascript-6">
    export default {
        name: 'brokerManageDetail',
        data() {
           
            return {
                activeName: 'first',
                brokerInfo: {},
                type2Name: {
                    new: '新建',
                    edit: '编辑',
                    view: '查看'
                },
                type: '',
                form: {
                    brokerType: '3',
                    cityId: '',
                    storeCode: '',
                    companyId: '',
                    storeId: '',
                    sectionId: '',
                    brokerName: '',
                    brokerPhone: '',
                    password: 'haoshenghuo',
                    brokerEmail: '',
                    newHouseRate: '',
                    insuranceRate: '',
                    propertyRate: '',
                    brokerLevel: '',
                    jobNumber: '',
                    basicSalary: '',

                    competence: ["1","2"]
                },
                rules: {
                    brokerType: [
                        {required: true, message: '请选择经纪人角色', trigger: 'blur'}
                    ],
                    cityId: [
                        {required: true, message: '请选择城市', trigger: 'blur'}
                    ],
                    storeCode: [
                        {required: true, message: '请输入门店编码'},
                        {pattern: /^[0-9]{1,10}$/, message: '门店编码格式不对', trigger: 'blur'}
                    ],
                    companyId: [
                        {required: true, message: '请选择所属公司', trigger: 'blur'}
                    ],
                    storeId: [
                        {required: true, message: '请选择所属门店', trigger: 'blur'}
                    ],
                    sectionId: [
                        {required: true, message: '请选择服务板块', trigger: 'blur'}
                    ],
                    brokerName: [
                        {required: true, message: '请输入用户姓名', trigger: 'change'},
                        { min: 1, max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
                    ],
                    brokerLevel: [
                        {required: true, message: '请选择经纪等级', trigger: 'change'}
                    ],
                    password: [
                        { min: 0, max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
                    ],
                    jobNumber: [
                        {required: true, message: '请输入工号', trigger: 'change'}
                    ],
                    basicSalary: [
                        {required: true, message: '请输入基本工资', trigger: 'change'}
                    ],
                    brokerPhone: [
                        {required: true, message: '请输入用户手机号', trigger: 'blur'},
                        {pattern: /^1[0-9]{10}$/, message: '手机号格式不对', trigger: 'blur'}
                    ],
                    brokerEmail: [
                        {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
                    ],

                    competence:[
                        {required: true, message: '请选择权限', trigger: ['blur', 'change']}
                    ],
                    newHouseRate: [
                        {required: true, message: '请输入新房分佣比例', trigger: ['blur', 'change']},
                        {pattern: /^(\d{1,2}(\.\d{1,2})?|100)$/, message: '输入格式不对，请输入0-100之间的正数，最多保留两位小数', trigger: 'blur'}
                    ],
                    insuranceRate: [
                        {required: true, message: '请输入保险分佣比例', trigger: ['blur', 'change']},
                        {pattern: /^(\d{1,2}(\.\d{1,2})?|100)$/, message: '输入格式不对，请输入0-100之间的正数，最多保留两位小数', trigger: 'blur'}
                    ],
                    propertyRate: [
                        {required: true, message: '请输入产权分佣比例', trigger: ['blur', 'change']},
                        {pattern: /^(\d{1,2}(\.\d{1,2})?|100)$/, message: '输入格式不对，请输入0-100之间的正数', trigger: 'blur'}
                    ]
                },

                brokerTypeList: [],
                allCityList: [],
                companyList: [],
                storeList: [],
                sectionList: [],
                brokerLevelList: [],
            }
        },
        created() {


        },
        mounted() {
            const query = this.$route.query;
            this.type = query.type;

            if (this.type !== 'new') {
                this.getBrokerInfo(+query.id)
            }

            if(this.type === 'view'){
                this.getAuthenticationInfo(query.brokerCode)
            }
            this.getAllCity()
            this.getBrokerType()
        },
        methods: {


            getAuthenticationInfo(brokerCode){
                this.$axios.post('/user/broker/getAuthInfo', {brokerCode}).then((res) => {
                    this.brokerInfo = res
                })
                
            },
            saveBroker() {
                let params = {
                    id: this.form.id,
                    brokerType: this.form.brokerType,
                    cityId: this.form.cityId,
                    companyId: this.form.companyId,
                    brokerName: this.form.brokerName,
                    brokerPhone: this.form.brokerPhone,
                    password: this.form.password,
                    brokerEmail: this.form.brokerEmail
                };
                let validateField = ['brokerType', 'cityId', 'companyId', 'brokerName', 'brokerPhone']

                if (params.brokerEmail) {
                    validateField.push('brokerEmail')
                }

                // 职业经纪人
                if (this.form.brokerType === '3') {
                    params.storeCode = this.form.storeCode;
                    params.storeId = this.form.storeId;
                    params.sectionId = this.form.sectionId;

                    validateField.push('storeId', 'storeCode', 'sectionId')
                }
                // 职业经纪人 经纪公司 经纪门店   含有权限
                if (this.form.brokerType === '3' || this.form.brokerType === '4' || this.form.brokerType === '5') {
                    let competenceMap = {
                        '1': 'newHouseRate',
                        '2': 'insuranceRate',
                        '3': 'propertyRate',
                    };
                    validateField.push('competence')

                    for (let key in competenceMap) {
                        const item = competenceMap[key]
                        if (this.form.competence.includes(key)) {
                            params[item] = Number(this.form[item])
                            validateField.push(item)
                        } else {
                            params[item] = -1
                        }
                    }
                }
                // 销售经理和置业顾问
                if (this.form.brokerType === '6' || this.form.brokerType === '8') {
                    params.jobNumber = this.form.jobNumber;
                    params.basicSalary = this.form.basicSalary;
                    params.brokerLevel = this.form.brokerLevel;
                    validateField.push('brokerLevel', 'jobNumber', 'basicSalary')
                }
                let validateFieldCount = 0;
                this.$refs.form.validateField(validateField, (valid) => {
                    console.log(valid);
                    // console.log(valid === '', '1' + valid + '1');
                    if (valid === '') {
                        validateFieldCount++;
                    }
                });
                console.log(validateField, validateFieldCount);
                if (validateField.length === validateFieldCount) {
                    const url = {
                        new: '/user/broker/save',
                        edit: '/user/broker/updateBroker'
                    }

                    console.log(params);
                    this.$axios.post(url[this.type], params).then((res) => {
                        //console.log(res);
                        this.$message.success(this.type2Name[this.type] + "经纪人成功")
                        this.returnList()
                        //this.brokerTypeList = res
                    })
                }
            },
            getAllCity() {
                this.$axios.post('/city/cityList', {}).then((res) => {
                    this.allCityList = res.cityList
                })
            },
            getBrokerType() {
                this.$axios.get("/user/broker/role/list").then((res) => {
                    this.brokerTypeList = res
                })
            },
            getCompanyListByCityId() {
                this.form.companyId = '';
                this.form.storeCode = '';
                this.form.storeId = '';
                this.form.sectionId = '';

                this.$axios.post("/user/broker/getCompanyListByCityId", {cityId: this.form.cityId}).then((res) => {
                    this.companyList = res
                })
            },
            getStoresByCompanyId() {
                this.form.storeId = ''
                this.form.storeCode = '';
                this.$axios.post("/user/broker/getStoresByCompanyId", {companyId: this.form.companyId}).then((res) => {
                    this.storeList = res
                })

                this.getBrokerLevel()
            },
            getBrokerLevel() {
                this.$axios.get("/user/broker/getBrokerLevel", {companyId: this.form.companyId}).then((res) => {
                    this.brokerLevelList = res
                })
            },
            getStoreByNumber(filed) {
                // 没有storeCode 只能单查公司
                if(typeof filed === 'object' && !this.form.storeCode){
                    this.getCompanyListByCityId()
                    this.form.companyId = filed.companyId
                    return false
                }

                // 118010002
                let storeNumber = this.form.storeCode;
                if (filed === 'storeId') {

                    const tempStoreNumber = this.storeList.find((item) => {
                        return item.id === this.form.storeId
                    }).storeNumber || '';
                    this.$axios.post("/user/broker/getStoreByNumber", {storeNumber: tempStoreNumber}).then((res) => {
                        const data = res[0];
                        this.form.storeCode = data.storeNumber;
                        this.sectionList = [{
                            areaId: data.areaId,
                            areaName: data.areaName,
                        }]
                        this.form.sectionId = data.areaId
                    })
                } else {
                    this.$axios.post("/user/broker/getStoreByNumber", {storeNumber}).then(async (res) => {
                        if (res.length) {
                            const data = res[0];
                            this.form.cityId = data.cityId;
                            await this.getCompanyListByCityId();
                            this.form.companyId = data.brokerCompanyId;
                            await this.getStoresByCompanyId();
                            this.form.storeId = data.id;
                            this.form.storeCode = data.storeNumber;
                            this.sectionList = [{
                                areaId: data.areaId,
                                areaName: data.areaName,
                            }]
                            this.form.sectionId = data.areaId
                        }
                    })
                }
            },
            returnList() {
                this.$router.push({path: "./brokerManage"})
            },

            getBrokerInfo(brokerId) {
                const renderCompetence = (competenceArr) => {
                    let competence = [];
                    competenceArr.forEach((item, index) => {
                        if (item > -1) {
                            competence.push(String(index + 1))
                        }
                    });
                    return competence
                }


                this.$axios.post('/user/broker/viewBroker', {brokerId}).then((res) => {
                    console.log(res);

                    //storeCode


                    this.form = {
                        id: res.id,
                        brokerType: String(res.brokerType),
                        cityId: String(res.cityId),
                        storeCode: res.storeCode,
                        companyId: res.companyId,
                        storeId: '',
                        sectionId: '',
                        brokerName: res.brokerName,
                        brokerPhone: res.brokerPhone,
                        password: res.password,
                        brokerEmail: res.brokerEmail || '',
                        newHouseRate: res.house !== -1 ? res.house : '',
                        insuranceRate: res.insurance !== -1 ? res.insurance : '',
                        propertyRate: res.property !== -1 ? res.property : '',
                        brokerLevel: res.brokerLevel,
                        jobNumber: res.jobNumber,
                        basicSalary: res.basicSalary,
                        competence: renderCompetence([res.house, res.insurance, res.property])
                    };


                    this.getStoreByNumber(res)
                })
            }
        },
        components: {},
        computed: {}
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus">

</style>
